const jwt = require('jsonwebtoken'),
	secret = '13166103561';

module.exports = class extends think.Service {

	/**
	 * @author: ares
	 * @date: 2018/5/25 11:42
	 * @description: 生成token
	 * @param {object}data     待签名的数据
	 * @returns {*}
	 */
	createToken(data) {
		// return jwt.sign(data, secret, {expiresIn: '1h'});
		return jwt.sign(data, secret);
	}

	/**
	 * @author: ares
	 * @date: 2018/5/25 11:43
	 * @description: 验证token
	 * @param {string}token    待验证的token
	 * @returns {Promise.<{}>}
	 */
	async verifyToken(token) {
		let result = {};
		await jwt.verify(token, secret, function (err, decoded) {
			if (err) {
				result.error = true;
				let msg = '';
				switch (err.message) {
					case 'jwt expired':
						msg = 'token失效';
						break;
					case 'jwt signature is required':
						msg = 'token未签名';
						break;
					case 'invalid signature':
						msg = 'token签名错误';
						break;
					case 'jwt audience invalid. expected: [OPTIONS AUDIENCE]':
						msg = 'token接受方不匹配';
						break;
					case 'jwt issuer invalid. expected: [OPTIONS ISSUER]':
						msg = 'token发行方不匹配';
						break;
					case 'jwt id invalid. expected: [OPTIONS JWT ID]':
						msg = 'JWT ID 不匹配';
						break;
					case 'jwt subject invalid. expected: [OPTIONS SUBJECT]':
						msg = 'JWT SUBJECT 不匹配';
						break;
					default:
						msg = 'token异常';
				}
				result.msg = msg;
			} else {
				result.error = false;
				result.data = decoded;
			}
		});
		return result;
	}

};
